package com.stox.core.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.stox.core.ui.swing.util.ThrowableReporter;
import com.stox.core.util.Constant;
import com.stox.core.util.PropertiesUtil;
import com.stox.ioc.Container;

public class AbstractDao {

	private static Connection connection;
	
	protected Connection getConnection(){
		if(connection == null){
			connection = createConnection();
		}
		return connection;
	}

	protected Connection getNullableConnection(){
		return connection;
	}
	
	protected Connection createConnection(){
		Connection connection = null;
		PropertiesUtil propertiesUtil = Container.get(PropertiesUtil.class);
		String installationPath = propertiesUtil.get(Constant.keyInstallationPath);
		String url = propertiesUtil.get("jdbc.stox.url.prefix")+installationPath + propertiesUtil.get("jdbc.stox.url.postfix");
		String username = propertiesUtil.get("jdbc.stox.username");
		String password = propertiesUtil.get("jdbc.stox.password");
		String driverClassName = propertiesUtil.get("jdbc.stox.driverClassName");
		
		try{
			Class.forName(driverClassName);
			connection = DriverManager.getConnection(url, username, password);
		}catch(Exception e){
			ThrowableReporter.report(e);
		}
		return connection;
	}
	
	protected void commit() throws SQLException{
		connection.createStatement().execute("commit");
	}
	
}
